package controller;

import data.DatabaseGateway;
import misc.Configurations;
import misc.Logger;
import misc.Utility;

public class LoginController {
    public enum LoginError{ok,badlogin,unknown};
    
    public LoginError isAuthorized(String username, String password)
                                                    throws Exception
    {
        int num=0;

        if(username=="" || password=="")
            return LoginError.badlogin;

        try
        {
            String query = "SELECT * FROM USERS WHERE Username='"+username+
                    "' AND HashedPassword='"+Utility.hashMD5(password)+"'";

            DatabaseGateway gw = new DatabaseGateway();
            gw.openConnection(Configurations.User,Configurations.Password,
                                Configurations.DatabaseName);
            num = gw.executeCount(query);
            gw.closeConnection();
        }
        catch(Exception e)
        {
            Logger.write(e.getMessage(),Logger.LogType.error);
            return LoginError.unknown;
        }

        if(num==1)
            return LoginError.ok;
        else
            return LoginError.badlogin;
    }
}
